import React, { PropTypes } from 'react'
import _ from 'lodash'
import ImageItem, { EmImgProcessType } from './image-item.jsx'
import { is, fromJS } from 'immutable'

class MediaSlider extends React.Component {
  constructor() {
    super();
    this.state = {
      index:-1,
      startX:'',
      startY:'',
      endX:'',
      endY:''
    };
  }

  touchStart(ev) {
    // 如果只有一个数据,则不响应
    if (this.props.data.length < 2) {
      return;
    }

    /*
     开始滑动的时候先关闭定时器
     * */
    if (this.intervalId) {
      clearInterval(this.intervalId)
    }

    this.setState({
      startX:ev.touches[0].pageX,
      startY:ev.touches[0].pageY
    })
  }

  touchEnd(ev, i) {
    let { data } = this.props
    // 如果只有一个数据,则不响应
    if (data.length < 2) {
      return;
    }

    this.setState({
      startX:'',
      startY:''
    })

    let direction = this.getSlideDirection(this.state.startX,
      this.state.startY,
      ev.changedTouches[0].pageX,
      ev.changedTouches[0].pageY);

    let ix = -1;
    switch (direction) {
      case 0:// "没滑动"
        break;
      case 1:// 向上
        break;
      case 2:// "向下"
        break;
      case 3:// "向左"
        ix = i + 1;
        if (ix >= data.length) {
          ix = 0;
        }
        break;
      case 4:// "向右"
        ix = i - 1;
        if (ix < 0) {
          ix = data.length - 1;
        }
        break;
      default:
    }
    if (ix !== -1) {
      this.setState({
        index:ix
      }, () => {
        this.intervalId = setInterval(() => {
          let idx = this.state.index + 1;
          if (idx > data.length - 1) {
            idx = 0;
          }
          this.setState({
            index:idx
          })
        }, 3000);
      });
    } else {
      this.intervalId = setInterval(() => {
        let idx = this.state.index + 1;
        if (idx > data.length - 1) {
          idx = 0;
        }
        this.setState({
          index:idx
        })
      }, 3000);
    }
  }

  getSlideAngle(dx, dy) {
    return ((Math.atan2(dy, dx)) * 180) / Math.PI;
  }

  getSlideDirection(startX, startY, endX, endY) {
    let dy = startY - endY;
    let dx = endX - startX;
    let result = 0;

    //如果滑动距离太短
    if (Math.abs(dx) < 5 && Math.abs(dy) < 5) {
      return result;
    }

    let angle = this.getSlideAngle(dx, dy);
    if (angle >= -45 && angle < 45) {
      result = 4;
    } else if (angle >= 45 && angle < 135) {
      result = 1;
    } else if (angle >= -135 && angle < -45) {
      result = 2;
    } else if ((angle >= 135 && angle <= 180) || (angle >= -180 && angle < -135)) {
      result = 3;
    }

    return result;
  }

  selHandle(i, e) {
    this.setState({ index:i });
  }

  shouldComponentUpdate(nextProps, nextState) {
    return !is(fromJS(this.props), fromJS(nextProps)) || !is(fromJS(this.state),fromJS(nextState))
  }

  componentWillReceiveProps(nextProps) {
    let { data } = nextProps
    let il = (data || []).length
    if (il !== 0) {
      if (il > 1) {
        this.setState({
          index:0
        }, () => {
          this.intervalId = setInterval(() => {
            let idx = this.state.index + 1;
            if (idx > data.length - 1) {
              idx = 0;
            }
            this.setState({
              index:idx
            })
          }, 3000);
        })
      } else {
        this.setState({
          index:0
        })
      }
    }
  }

  componentDidMount() {
  }

  // 在组件从 DOM 中移除的时候立刻被调用
  componentWillUnmount() {
    if (this.intervalId) {
      clearInterval(this.intervalId)
    }
  }

  render() {
    let { data, height, aspectRatio, quality } = this.props
    data = data || []

    let items = []
    if (data.length > 0 && this.state.index >= 0) {
      items.push(data[this.state.index])
    }

    return (
      <div className='carousel-picture'>
        <ul className='picture-list'>
          {
            _.map(items, (v, k) => {
              return (
                <li
                  key={k}
                  className='picture-item'
                  onTouchStart={ev => { this.touchStart(ev) }}
                  onTouchEnd={ev => { this.touchEnd(ev, this.state.index) }}
                >
                  <ImageItem
                    aspectRatio={aspectRatio}
                    imageUrl={v.imageUrl}
                    linkUrl={v.linkUrl}
                    processType={EmImgProcessType.emGD_HW_S}
                    quality={quality}
                    height={height}
                  />
                </li>
              )
            })
          }
        </ul>
        <div className='point-box'>
          {
            _.map(items, (v, k) => {
              if (k === this.state.index) {
                return <li key={k} className='point point-activate' onClick={ev => { this.selHandle(k, ev) }} />
              }

              return <li key={k} className='point' onClick={ev => { this.selHandle(k, ev) }} />
            })
          }
        </div>
      </div>
    )
  }
}

/*
 data   : 图片数据
 height : 高度
 * */
MediaSlider.propTypes = {
  data: PropTypes.array.isRequired,
  height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  aspectRatio: PropTypes.string.isRequired,
  quality: PropTypes.number.isRequired,
}

/*
 let data = [
   {
     imageUrl:'http://img2.jsbn.com/venus/vda/20161224/14825507343876028_1920x680.jpg',
     linkUrl:'cq.jsbn.com',
   },
   {
     imageUrl:'http://img2.jsbn.com/venus/vda/20161122/14797950401621928_1919x680.jpg',
     linkUrl:'cq.jsbn.com',
   }
 ]
 <MediaSlider
   aspectRatio='3:2'
   quality={90}
   height={800}
   data={data}
 />
* */

export default MediaSlider
